package day19.zhiyou100;

// 测试类
class TestAccount {

    public static void main(String[] args) {
        Account01 account01 = new Account01("10001",1000);
        System.out.println("account014对象的地址为：" + account01);
        // 创建两个用户线程
        UserThread01 t1 = new UserThread01(account01,"t1");
        System.out.println("t1对象的地址为：" + t1);
        UserThread01 t2 = new UserThread01(account01,"t2");
        System.out.println("t2对象的地址为：" + t2);
        UserThread01.money = 500;// 取钱金额
        t1.start();
        t2.start();
    }

}

// 定义用户线程
class UserThread01 extends Thread {
    private Account01 account01;
    static double money;
    public UserThread01(Account01 account01,String name) {
        super(name);
        this.account01 = account01;
    }

    // 重写run方法
    @Override
    public void run() {
        account01.withdraw(money);
        System.out.println(this.getName() + "---->取钱后余额为：" + account01.getBalance());
    }

}

public class Account01 {

    private String no;
    private double balance;

    // 添加一个取钱的功能
    public void withdraw(double money) {
        synchronized (this) {// this此时指代的是当前类的对象
            System.out.println("当前的对象为：---->" + this);
            if (money <= balance) {
                double before = balance;
                double after = balance - money;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                balance = after;
            }
        }
    }

    public Account01() {
    }

    public Account01(String no, double balance) {
        this.no = no;
        this.balance = balance;
    }

    public String getNo() {
        return no;
    }

    public void setNo(String no) {
        this.no = no;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }
}
